import React, { useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { ChatProvider, useChatContext } from './contexts/ChatContext';
import MainLayout from './components/layouts/MainLayout';
import Chat from './pages/Chat';
import Settings from './pages/Settings';
import { chatService } from './services/api';

// 模拟数据，在API不可用时使用
const MOCK_CONVERSATIONS = [
  { id: 'mock1', title: '模拟对话1', created_at: new Date().toISOString() },
  { id: 'mock2', title: '模拟对话2', created_at: new Date().toISOString() }
];

const MOCK_MESSAGES = {
  'mock1': [
    { id: 'msg1', role: 'user', content: '这是一条模拟消息', timestamp: new Date().toISOString() },
    { id: 'msg2', role: 'assistant', content: '这是模拟回复，API连接不可用，请检查后端服务是否运行', timestamp: new Date().toISOString() }
  ]
};

// 顶部导航栏组件
const NavBar = () => (
  <div className="bg-white border-b flex items-center justify-between px-4 h-14">
    <div className="flex items-center">
      <div className="text-blue-600 font-bold text-2xl flex items-center">
        <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" className="w-8 h-8 mr-2">
          <path d="M16 5.33a4.67 4.67 0 100 9.34 4.67 4.67 0 000-9.34zM10.4 21.33a5.6 5.6 0 00-5.6 5.6v.94h22.4v-.94a5.6 5.6 0 00-5.6-5.6H10.4z" fill="currentColor" />
        </svg>
        Qwen
      </div>
    </div>
    <div className="flex items-center space-x-2">
      <button className="p-2 rounded-full hover:bg-gray-100">
        <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
      </button>
      <div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white font-bold">
        B
      </div>
    </div>
  </div>
);

function AppContent() {
  const { dispatch } = useChatContext();

  // 初始化应用
  useEffect(() => {
    const loadInitialData = async () => {
      try {
        // 获取会话列表
        let conversations = await chatService.getConversations();

        // 如果会话列表为空，使用模拟数据
        if (!conversations || conversations.length === 0) {
          console.log('使用模拟会话数据');
          conversations = MOCK_CONVERSATIONS;
        }

        dispatch({ type: 'SET_CONVERSATIONS', payload: conversations });

        // 如果有会话，设置当前会话为第一个
        if (conversations.length > 0) {
          dispatch({ type: 'SET_CURRENT_CONVERSATION', payload: conversations[0].id });

          // 获取当前会话的消息
          let messages;
          try {
            messages = await chatService.getMessages(conversations[0].id);

            // 如果消息为空，使用模拟数据
            if (!messages || messages.length === 0 && conversations[0].id.startsWith('mock')) {
              console.log('使用模拟消息数据');
              messages = MOCK_MESSAGES[conversations[0].id] || [];
            }
          } catch (error) {
            console.error('获取消息失败，使用模拟数据', error);
            if (conversations[0].id.startsWith('mock')) {
              messages = MOCK_MESSAGES[conversations[0].id] || [];
            } else {
              messages = [];
            }
          }

          dispatch({ type: 'SET_MESSAGES', payload: messages });
        }
      } catch (error) {
        console.error('加载初始数据失败，使用模拟数据', error);
        // 使用模拟数据
        dispatch({ type: 'SET_CONVERSATIONS', payload: MOCK_CONVERSATIONS });
        dispatch({ type: 'SET_CURRENT_CONVERSATION', payload: MOCK_CONVERSATIONS[0].id });
        dispatch({ type: 'SET_MESSAGES', payload: MOCK_MESSAGES[MOCK_CONVERSATIONS[0].id] });
      }
    };

    loadInitialData();
  }, [dispatch]);

  return (
    <Router>
      <div className="flex flex-col h-screen bg-gray-50">
        <NavBar />
        <div className="flex-1 overflow-hidden flex flex-col">
          <Routes>
            <Route path="/" element={<Chat />} />
            <Route path="/settings" element={<Settings />} />
          </Routes>
        </div>
      </div>
    </Router>
  );
}

function App() {
  return (
    <ChatProvider>
      <AppContent />
    </ChatProvider>
  );
}

export default App;